<template>
  <div class="test-question-list">
    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <div class="header-warp">
        <div>
          <el-button text type="primary" icon="el-icon-plus" @click="videosList">
            添加学习资料
          </el-button>
          <el-button text type="primary" icon="el-icon-plus" @click="paperList">
            添加试卷
          </el-button>
          <el-button text type="danger" icon="el-icon-delete" :disabled="current.length <= 0" @click="batchDeletion">
            批量删除
          </el-button>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" style="border: none;">
      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="学习视频" name="1">
            <div>
              <el-table style="width: 100%" :data="list" border :row-key="getRowKeyOfTarget" @selection-change="selectionChange">
                <el-table-column label="学习视频" align="center">
                  <el-table-column type="selection" align="center" :reserve-selection="true" />
                  <el-table-column width="370" label="视频列表" align="center">
                    <template v-slot="{ row }">
                      <video width="350" height="200" :src="row.path" @click="playToVideo(row)" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" label="视频名称" align="center" />
                  <el-table-column prop="type" label="视频类别" align="center" />
                  <el-table-column label="创建时间" prop="created_at" align="center" />
                  <el-table-column label="最后修改时间" prop="updated_at" align="center" />
                  <el-table-column align="center" prop="action" label="操作">
                    <template v-slot="{ row }">
                      <el-button type="danger" icon="el-icon-delete" circle @click="deleteStudy(row)" />
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
              <div class="page-ination">
                <Pagination style="margin-top: 0; padding-bottom: 0;" :total="pageInfo.total" :limit="pageInfo.paginate" @pagination="pageMp" />
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="学习文件" name="2">
            <div>
              <el-table style="width: 100%" :data="file" border :row-key="getRowKeyOfTarget" @selection-change="selectionChange">
                <el-table-column label="学习文件" align="center">
                  <el-table-column type="selection" align="center" :reserve-selection="true" />
                  <el-table-column prop="name" label="文件名称" align="center" />
                  <el-table-column prop="type" label="文件类别" align="center" />
                  <el-table-column label="创建时间" prop="created_at" align="center" />
                  <el-table-column label="最后修改时间" prop="updated_at" align="center" />
                  <el-table-column align="center" prop="action" label="操作">
                    <template v-slot="{ row }">
                      <el-button circle plain icon="el-icon-view" @click="preview(row)" />
                      <el-button plain icon="el-icon-download" circle @click="downLoad(row)" />
                      <el-button type="danger" icon="el-icon-delete" circle @click="deleteStudy(row)" />
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
            <div class="page-ination">
              <Pagination style="margin-top: 0; padding-bottom: 0;" :total="pageFile.total" :limit="pageFile.paginate" @pagination="pageFil" />
            </div>
          </el-tab-pane>
          <el-tab-pane label="试卷" name="3">
            <el-table :data="showPaperList">
              <el-table-column label="试卷" align="center">
                <el-table-column label="试卷名称" prop="title" align="center" />
                <el-table-column label="及格分" prop="pass" align="center">
                  <template v-slot="{ row }"><span> {{ row.pass ?? 0 }} </span></template>
                </el-table-column>
                <el-table-column label="满分" prop="points" align="center" />
                <el-table-column label="是否启用" prop="open" align="center">
                  <template v-slot="{ row }">
                    <span>{{ row.open === 1 ? '启用' : '未启用' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="created_at" align="center" />
                <el-table-column label="最后修改时间" prop="updated_at" align="center" />
                <el-table-column label="操作" align="center">
                  <template v-slot="{ row }">
                    <el-button circle plain type="primary" icon="el-icon-edit" @click="changeTime(row)" />
                    <el-button type="danger" icon="el-icon-delete" circle @click="deletePaper(row)" />
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

      </div>
    </el-card>
    <div>
      <DialogContent
        ref="dialogContent"
        :visible.sync="studyDocuments"
        width="60%"
        :close-on-click-modal="false"
      >
        <pdf
          ref="pdf"
          :src="documents"
          :page="pageNum"
          @progress="loadedRatio = $event"
          @num-pages="pageTotalNum = $event"
        />
        <div slot="footer" class="dialog-footer">
          <div class="page" style="margin-top: 10px; color: #409eff">
            {{ pageNum }} / {{ pageTotalNum }}
          </div>
          <div class="btnUD">
            <el-button
              round
              type="info"
              style="height: 30px; width: 80px; margin-right: 40px"
              size="mini"
              @click="prePage"
            >上一页</el-button>
            <el-button round type="info" style="height: 30px; width: 80px" size="mini" @click="nextPage">下一页</el-button>
          </div>
        </div>
      </DialogContent>
      <!-- <el-dialog >

      </el-dialog> -->
    </div>
    <div>
      <el-dialog
        :visible.sync="dialogVisible"
        title="添加学习资料"
        :close-on-click-modal="false"
        width="40%"
      >
        <el-radio v-model="page.type" label="mp4" @change="type">视频</el-radio>
        <el-radio v-model="page.type" label="pdf" @change="type">文件</el-radio>
        <el-table style="width: 100%" :data="videos" :row-key="getRowKeyOfTarget" @selection-change="handleSelectionChange">
          <el-table-column type="selection" />
          <el-table-column label="类别" align="center">
            <template slot-scope="scope">
              {{ scope.row.type == 'mp4' ? '视频' : '文件' }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" align="center" />
        </el-table>
        <Pagination :total="page.total" :limit="page.paginate" @pagination="pagination" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addStudies">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :visible.sync="testPaper"
        title="添加试卷"
        :close-on-click-modal="false"
        width="60%"
      >
        <el-table style="width: 100%" :data="papersList" :row-key="getRowKeyOfTarget" @selection-change="paperChange">
          <el-table-column type="selection" />
          <el-table-column prop="title" label="试卷名称" align="center" />
          <el-table-column prop="pass" label="及格分" align="center" />
          <el-table-column prop="points" label="满分" align="center" />
          <el-table-column prop="created_at" label="创建时间" align="center" />
          <el-table-column prop="updated_at" label="最后修改时间" align="center" />
        </el-table>
        <Pagination :total="pageTransfer.total" :limit="pageTransfer.paginate" @pagination="paperPages" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="testPaper = false">取 消</el-button>
          <el-button type="primary" @click="addPaper">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        width="35%"
        :visible.sync="paperTime"
        :close-on-click-modal="false"
        :title="forms ? '设置考试时间' : '修改考试时间'"
      >
        <el-date-picker
          v-model="testTime"
          value-format="yyyy-MM-dd hh:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="考试开始时间"
          end-placeholder="考试结束时间"
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="paperTime = false">取 消</el-button>
          <el-button type="primary" @click="testTimes">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        width="35%"
        :visible.sync="playVideo"
        :close-on-click-modal="false"
        :title="video.videoTitle"
      >
        <video width="100%" style="max-height: 65vh;" :src="video.videoPath" controls />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import DialogContent from '@/components/DialogContent/index.vue'
import pdf from 'vue-pdf'
import { courseDetail, videosList, addStudies, deleteStudies, addPapers, deletePaper, changePaperTime } from '@/api/train'
import { getPaper } from '@/api/examination'
export default {
  components: {
    Pagination,
    pdf,
    DialogContent
  },
  data() {
    return {
      list: [],
      file: [],
      title: '',
      activeName: '1',
      dialogVisible: false,
      studyDocuments: false,
      playVideo: false,
      testPaper: false,
      paperTime: false,
      video: {
        videoPath: null,
        videoTitle: ''
      },
      documents: '',
      videos: [],
      current: [],
      delete_id: {
        course_id: '',
        study_id: []
      },
      currentItem: [],
      deleteItemInfo: {
        deleteList: [],
        deletionFailureList: [],
        boundIds: [],
        delList: []
      },
      page: {
        paginate: 10,
        page: 1,
        total: 1,
        type: ''
      },
      pageInfo: {
        paginate: 10,
        page: 1,
        total: 1
      },
      pageFile: {
        paginate: 10,
        page: 1,
        total: 1
      },
      learnMaterials: {
        course_id: '',
        study: []
      },
      pageNum: 1, // 当前页
      pageTotalNum: 1, // 总页数
      pageTransfer: {
        paginate: 10,
        page: 1,
        total: 1,
        points: null,
        pass: null,
        course_id: this.$route.params.id
      },
      papersList: [],
      testTime: '',
      studyTrain: {
        course_id: null,
        train: null
      },
      paperID: '',
      showPaperList: [],
      testPaperId: '',
      forms: null,
      changeTimeId: ''
    }
  },
  created() {
    this.detail()
    this.files()
    this.showPaper()
  },
  methods: {
    getRowKeyOfTarget(row) {
      return row.id
    },
    async detail() {
      const params = {
        paginate: this.pageInfo.paginate,
        page: this.pageInfo.page,
        allStudy: 1,
        type: 'mp4',
        course_id: this.$route.params.id
      }
      const res = await courseDetail(this.$route.params.id, params)
      this.list = res.data
      this.pageInfo.total = res.meta.total
      console.log(res, 999)
    },
    async files() {
      const params = {
        paginate: this.pageFile.paginate,
        page: this.pageFile.page,
        allStudy: 1,
        type: 'pdf',
        course_id: this.$route.params.id
      }
      const res = await courseDetail(this.$route.params.id, params)
      this.file = res.data
      this.pageFile.total = res.meta.total
      console.log(res, 888)
    },
    async showPaper() {
      const res = await courseDetail(this.$route.params.id)
      console.log(res, 321123)
      this.showPaperList = res.data.paper
    },
    async videosList() {
      this.dialogVisible = true
      const params = {
        paginate: this.page.paginate,
        page: this.page.page,
        type: this.page.type,
        course_id: this.$route.params.id
      }
      console.log(this.pageInfo, 6666)
      const res = await videosList(params)
      console.log(res, 111)
      this.videos = res.data.data
      this.page.total = res.data.total
    },
    paperList() {
      this.testPaper = true
      const params = this.pageTransfer
      console.log('params ------>', params)
      getPaper(params)
        .then((res) => {
          console.log(res, '123123123123')
          this.papersList = res.data
          this.pageTransfer.total = res.meta.total
        })
        .catch((err) => {
          console.log(err)
        })
    },
    paperChange(e) {
      this.paperID = e.map(item => item.id)
      console.log(this.paperID, 123456789)
    },
    addPaper() {
      this.paperTime = true
      this.forms = true
    },
    deletePaper(row) {
      const params = {
        paper_id: row.id,
        course_id: this.$route.params.id
      }
      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deletePaper(params)
            .then((res) => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.showPaper()
            })
        })
    },
    type() {
      console.log(this.pageInfo, 654321)
      this.videosList()
    },
    handleSizeChange(e) {
      this.pageInfo.paginate = e
      this.pageInfo.page = 1
      this.getTestList()
      scrollTo(0, 800)
    },

    handleCurrentChange(e) {
      this.pageInfo.page = e
      this.getTestList()
      scrollTo(0, 800)
    },
    // 多选
    handleSelectionChange(e) {
      if (this.paperId) {
        this.currentItem = e.map((item, index) => {
          return { ...item, order: index + 1 }
        })
      } else this.currentItem = e.map(item => item.id)
      this.deleteItemInfo.deleteList = e
      console.log(JSON.stringify(this.currentItem), 654)
    },
    playToVideo(row) {
      this.playVideo = true
      this.video.videoTitle = row.name
      this.video.videoPath = row.path
    },
    selectionChange(e) {
      if (this.paperId) {
        this.current = e.map((item, index) => {
          return { ...item, order: index + 1 }
        })
      } else this.current = e.map(item => item.id)
    },
    async batchDeletion() {
      this.$confirm('是否删除', '提示', { type: 'warning' })
        .then(() => {
          const id = JSON.stringify(this.current)
          this.deleteItemInfo.delList = this.current
          this.batchDeletionApi(id)
        })
    },
    async batchDeletionApi(id) {
      console.log(id, 99999)
      this.delete_id.course_id = this.$route.params.id
      this.delete_id.study_id = id
      deleteStudies(this.delete_id)
        .then((res) => {
          this.$message({
            type: 'success',
            message: '删除课程成功'
          })
          this.detail()
          this.files()
        })
    },
    preview(row) {
      this.documents = row.path
      this.studyDocuments = true
    },
    downLoad(row) {
      window.location.href = row.path
    },
    deleteStudy(row) {
      const id = JSON.stringify([row.id])
      console.log(id, 250)
      this.delete_id.course_id = this.$route.params.id
      this.delete_id.study_id = id
      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteStudies(this.delete_id)
            .then((res) => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.detail()
              this.files()
            })
        })
    },
    addStudies() {
      this.learnMaterials.study = JSON.stringify(this.currentItem)
      this.learnMaterials.course_id = this.$route.params.id
      addStudies(this.learnMaterials)
        .then(() => {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.detail()
          this.files()
          this.dialogVisible = false
        })
        .catch(err => {
          console.log(err)
          this.$message({
            message: '请勿选择已经添加过的学习资料',
            type: 'error'
          })
        })
    },
    pagination(e) {
      this.page.page = e.page
      this.page.paginate = e.limit
      this.videosList()
    },
    pageMp(e) {
      this.pageInfo.page = e.page
      this.pageInfo.paginate = e.limit
      this.detail()
    },
    pageFil(e) {
      this.pageFile.page = e.page
      this.pageFile.paginate = e.limit
      this.files()
    },
    paperPages(e) {
      this.pageTransfer.page = e.page
      this.pageTransfer.paginate = e.limit
      this.paperList()
    },
    handleClick(type, e) {
      switch (this.activeName) {
        case '1':
          break
        case '2':
          break
        case '3':
          break
      }
    },
    prePage() {
      let page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
      this.$refs.dialogContent.resettingScroll()
    },

    // 下一页
    nextPage() {
      let page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
      this.$refs.dialogContent.resettingScroll()
    },
    changeTime(row) {
      this.forms = false
      this.paperTime = true
      this.changeTimeId = row.id
      // const date = {
      //   paper_id: row.id,
      //   course_id: this.$route.params.id,
      //   start_at: this.testTime[0],
      //   end_at: this.testTime[1]
      // }
      // changePaperTime(date)
      //   .then(() => {
      //     this.$message({
      //       message: '修改考试时间成功',
      //       type: 'success'
      //     })
      //     this.showPaper()
      //   })
      //   .catch(err => {
      //     console.log(err)
      //   })
    },
    testTimes() {
      if (this.forms) {
        var trains = { train: [] }
        for (let i = 0; i < this.paperID.length; i++) {
          const c = {
            paper_id: this.paperID[i],
            start_at: this.testTime[0],
            end_at: this.testTime[1]
          }
          trains.train.push(c)
        }
        this.studyTrain.train = trains.train
        this.studyTrain.course_id = this.$route.params.id
        console.log(JSON.stringify(this.studyTrain.train), 753)
        addPapers({ course_id: this.studyTrain.course_id, train: JSON.stringify(this.studyTrain.train) })
          .then(() => {
            this.$message({
              message: '添加试卷成功',
              type: 'success'
            })
            this.paperList()
            this.paperTime = false
            this.testPaper = false
            this.showPaper()
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        const date = {
          paper_id: this.changeTimeId,
          course_id: this.$route.params.id,
          start_at: this.testTime[0],
          end_at: this.testTime[1]
        }
        changePaperTime(date)
          .then(() => {
            this.$message({
              message: '修改考试时间成功',
              type: 'success'
            })
            this.paperTime = false
            this.showPaper()
          })
          .catch(err => {
            console.log(err)
          })
      }
    }
  }
}
</script>
<style scoped lang='scss'>
.test-question-list {
  padding: 20px;

  .header-warp {
    //margin: 20px 0;
    display: flex;
    justify-content: space-between;
  }

}

.pagination-warp {
  margin-top: 20px;
}
.dialog-footer {
  text-align: center;

  .page {
    font-weight: 600;
    margin-bottom: 20px;
  }

  .btnUD {
    text-align: center;
  }
}
</style>
